package helper

import (
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/gin-gonic/gin"
)

// QueryDbs 查询 DB
// @Summary 查询 DB
// @Description 查询 DB
// @Tags API.Helper
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Success 200 {object} response.TResponse{data=vo.SearchCacheVO}
// @Failure 400 {object}  response.TResponse{data=interface{}}
// @Router /api/helper/data/dbs [get]
// @Security LoginToken
func (h helperController) QueryDbs(c *gin.Context) {
	dbs, err := h.helperService.QueryDbs(c)
	dbsMap, _ := convertor.StructToMap(dbs)
	if err == nil {
		response.Success(c, "获取数据库成功", dbsMap)
	}
}

// QueryTables 查询 Table
// @Summary 查询 Table
// @Description 查询 Table
// @Tags API.Helper
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Param dbName formData string true "数据库名称"
// @Success 200 {object} response.TResponse{data=vo.DbsVO}
// @Failure 400 {object}  response.TResponse{data=interface{}}
// @Router /api/helper/data/tables [post]
// @Security LoginToken
func (h helperController) QueryTables(c *gin.Context) {
	var dbTableReq QO.DbTableReq
	if err := c.ShouldBind(&dbTableReq); err != nil {
		response.Fail(c, code.ParamBindError, code.Text(code.ParamBindError), gin.H{"realErr": err})
		return
	}
	tables, err := h.helperService.QueryTables(c, dbTableReq)
	tablesMap, _ := convertor.StructToMap(tables)
	if err == nil {
		response.Success(c, "获取表数据成功", tablesMap)
	}
}

// SearchMysql 执行 SQL 语句
// @Summary 执行 SQL 语句
// @Description 执行 SQL 语句
// @Tags API.Helper
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Param dbName formData string true "数据库名称"
// @Param tableName formData string true "数据表名称"
// @Param sql formData string true "SQL 语句"
// @Success 200 {object} response.TResponse{data=vo.DbTableVO}
// @Failure 400 {object}  response.TResponse{data=interface{}}
// @Router /api/helper/data/mysql [post]
// @Security LoginToken
func (h helperController) SearchMysql(c *gin.Context) {
	var searchMysqlReq QO.SearchMysqlReq
	if err := c.ShouldBind(&searchMysqlReq); err != nil {
		response.Fail(c, code.ParamBindError, code.Text(code.ParamBindError), gin.H{"realErr": err})
		return
	}
	searchMysqlData, err := h.helperService.SearchMysql(c, searchMysqlReq)
	toMap, _ := convertor.StructToMap(searchMysqlData)
	if err == nil {
		response.Success(c, "获取数据成功", toMap)
	}
}
